//模块配置信息
require.config({
	//baseUrl: "./",
	paths: {
		//工具模块
		'less': 'tools/less.min',
		'jquery': 'tools/jquery.min',
		'bootstrap': 'tools/bootstrap.min',
		'handlebars': 'tools/handlebars',

		//配置模块
		'config': './config',
		"appConfig":"./appConfig",
		'showBigImg':'modules/showBigImg',
		'top_bar': 'modules/top_bar',
		'problem': 'modules/problem',
		'ask': 'modules/ask',
		'modal_template': 'modules/modal_template',
		'cookie': 'modules/cookie',
		'check_log': 'modules/check_log',
		'login': 'modules/login',
		'other_log': 'modules/login',
		'reg': 'modules/reg',
		'user': 'modules/user',
		'userProblem':'modules/userProblem',
		'uploadFile':'modules/uploadFile'　　
	},
	skim: {  //配置依赖关系与接口
		"bootstrap": {	// bootstrap依赖jquery库
			deps: ['jquery'],
			exports: 'bootstrap'
		},
		"handlebars": {
			exports: 'Handlebars'
		},
		"user": {
			deps: ['modal_template']
		}
	}
});
/************************************header***************************************/
//加载顶栏top_bar模块
require(['top_bar'], function(top_bar){
	top_bar();
});
/************************************content***************************************/
require(['jquery','handlebars','userProblem','cookie','config','uploadFile','showBigImg','less'], function ($,Handlebars,userProblem,cookie,config,uploadFile,showBigImg){
var avatarUrl,pageBelongToId,loginUserId;
$(document).ready(function(){
	require(['bootstrap']);//为了绑定登陆注册按钮弹窗事件
	var url=window.location.search;
	pageBelongToId=url.substring(url.indexOf("=")+1);
	loginUserId=cookie.getCookie("userId");
	fetchUserData(pageBelongToId);
	getRelationBetweenUser(loginUserId,pageBelongToId);
	//fetchUserData("55743953c917531899b38cc0");
});
//确定当前页面所属用户与登陆用户的关系
function getRelationBetweenUser(userId1,userId2) {
	var url=config.api.getRelationBetweenUser[0].replace(/\<\w+1\>/,userId1);
	url=url.replace(/\<\w+2\>/,userId2);
	$.ajax({
		url:url,
		type:config.api.getRelationBetweenUser[1],
		success:function(d){
			if(d.relation==1||d.relation==3){
				$("#followThisGuy").attr("id","unfollowThisGuy").text("取消关注");
			}
		}
	});
}
function fetchUserData(pageBelongToId){
	$.ajax({
		url:config.api.getUserInfo[0].replace(/\<\w+\>/,pageBelongToId),
		type:config.api.getUserInfo[1],
		success:function(d){
			console.log(d);
			avatarUrl=d.user.avatarUrl||"image/emptyAvatar.jpg";
			handlebarsRender("#userInfo-template",".container",d);
			$(".tabs").delegate("li","click",function(){
				var ref=$(this).data("ref");
				$(".tab-nav").removeClass("active");
				$(this).addClass("active");
				$(".tabs-body").removeClass("show").parent().find(".tabs-body[data-ref="+ref+"]").addClass("show");
			});//绑定事件
			$("#fansLink").attr("href","othersFans.html?userId="+d.user.userId);
			$("#followLink").attr("href","othersFollow.html?userId="+d.user.userId);
			$("#followBtnContainer").on("click","#followThisGuy",function() {
				followUser(pageBelongToId);
			});
			$("#followBtnContainer").on("click","#unfollowThisGuy",function() {
				unfollowUser(pageBelongToId);
			});
			//获取内容数据
			var date = new Date();
			var timestamp = date.getTime();
			getProblemList(0, 20, timestamp, pageBelongToId,avatarUrl);
		    getComments(0, 20, timestamp, pageBelongToId,avatarUrl);
			getWorks();
		}
	});
}
function getProblemList(skip, total, timestamp, userId,avatarUrl){
	var theUrl=config['api']['getAllProblemOfUser'][0].replace(/\<\w+\>/,userId);
	var request = $.ajax({
		url: theUrl,
		type: config['api']['getAllProblemOfUser'][1],
		data: {
			skip: skip,
			total: total,
			timestamp: timestamp,
			userId: userId
		},
		dataType: 'json',
		async: true,
		error: function(err){
			console.log('get problem failed!');
		},
		success: function(data){
			//中心问题模板，用hanlebars生成
			var source = $("#problems-template").html();
			var template = Handlebars.compile(source);
			//定义helper，判断返还图片是否为数组
			Handlebars.registerHelper('if_zan', function(value, options){
				if(value == 1){
					return options.fn(this);
				}
				else{
					return options.inverse(this);
				}
			});
			//定义helper，判断头像是否为空
			Handlebars.registerHelper('if_empty', function(value, options){
				if(value == ''){
					return options.fn(this);
				}
				else{
					return options.inverse(this);
				}
			});
			//添加hasImage标记+处理时间戳
			for (var i = 0; i < data['problems'].length; i++) {
				if (data['problems'][i]['image'] != ''){
					data['problems'][i]['hasImage'] = true;
				}

				var timestamp = data['problems'][i]['timestamp'];
				var exp = new Date();
				exp.setTime(timestamp);
				//把时间分开装入数组，对只有一位的值进行前补0处理
				var timeArray = [exp.getFullYear(), (exp.getMonth()+1), 
					exp.getDate(), exp.getHours(), exp.getMinutes(), exp.getSeconds()];
				for (var j = 0; j < 6; j++) {
					if (timeArray[j].toString().length == 1){
						timeArray[j] = '0' + timeArray[j];
					}
				}
				var publishTime = timeArray[0] + '.' + timeArray[1] + '.' + timeArray[2]
						+ '  ' + timeArray[3] + ':' + timeArray[4] + ':' + timeArray[5];
				data['problems'][i]['publishTime'] = publishTime;
			}
			
			data.avatarUrl=avatarUrl;
			console.log("提问",data);
			var myQuestionsComments={};//用以记录评论数据的状态
			$('#myQuestion').html(template(data));
			
			// //调整中心问题区头像的高度为其宽度
			// var leftColWidth = $('.left-col:eq(0) img').css('width');
			// $('.left-col').css('height', leftColWidth);
			// //更改浏览器窗口大小时
			// $(window).resize(function(){
			// 	var leftColWidth = $('.left-col:eq(0) img').css('width');
			// 	$('.left-col').css('height', leftColWidth);
			// });
		}
	});
}
function getComments(skip, total, timestamp, userId,avatarUrl){
	var theUrl=config['api']['getAllCommentsOfUser'][0].replace(/\<\w+\>/,userId);
	var request = $.ajax({
		url: theUrl,
		type: config['api']['getAllCommentsOfUser'][1],
		data: {
			skip: skip,
			total: total,
			timestamp: timestamp,
			userId: userId
		},
		dataType: 'json',
		async: true,
		error: function(err){
			console.log('get comments failed!');
		},
		success: function(data){
			console.log("评论",data);
			//中心问题模板，用hanlebars生成
			var source = $("#comments").html();
			var template = Handlebars.compile(source);
			//定义helper，判断返还图片是否为数组
			Handlebars.registerHelper('if_zan', function(value, options){
				if(value == 1){
					return options.fn(this);
				}
				else{
					return options.inverse(this);
				}
			});
			//定义helper，判断头像是否为空
			Handlebars.registerHelper('if_empty', function(value, options){
				if(value == ''){
					return options.fn(this);
				}
				else{
					return options.inverse(this);
				}
			});
			//添加hasImage标记+处理时间戳
			for (var i = 0; i < data['comments'].length; i++) {
				if (data['comments'][i].problem['image'] != ''){
					data['comments'][i].problem['hasImage'] = true;
				}

				var timestamp = data['comments'][i].problem['timestamp'];
				var exp = new Date();
				exp.setTime(timestamp);
				//把时间分开装入数组，对只有一位的值进行前补0处理
				var timeArray = [exp.getFullYear(), (exp.getMonth()+1), 
					exp.getDate(), exp.getHours(), exp.getMinutes(), exp.getSeconds()];
				for (var j = 0; j < 6; j++) {
					if (timeArray[j].toString().length == 1){
						timeArray[j] = '0' + timeArray[j];
					}
				}
				var publishTime = timeArray[0] + '.' + timeArray[1] + '.' + timeArray[2]
						+ '  ' + timeArray[3] + ':' + timeArray[4] + ':' + timeArray[5];
				data['comments'][i].problem['publishTime'] = publishTime;
			}
			
			var problems=data.comments.map(function(comment){
				return comment.problem;
			});
			var problemsData={
				problems:problems,
				avatarUrl:avatarUrl
			};
			console.log("构造的problemData",problemsData);
			var $commentsProblemsList=$('#myComment');
			$commentsProblemsList.html(template(problemsData));

			//调整中心问题区头像的高度为其宽度
			var leftColWidth = $('.left-col:eq(0) img').css('width');
			$('.left-col').css('height', leftColWidth);
			//更改浏览器窗口大小时
			$(window).resize(function(){
				var leftColWidth = $('.left-col:eq(0) img').css('width');
				$('.left-col').css('height', leftColWidth);
			});
		}
	});
}
function handlebarsRender(tplSelector,destSelector,data){
	//用jquery获取模板
	var source   = $(tplSelector).html();
	//预编译模板
	var template = Handlebars.compile(source);
	//匹配json内容
	var html = template(data);
	//输入模板
	$(destSelector).html(html);
}
Handlebars.registerHelper("firstInRow",function(index,options){
	if(index%4==0){
		return options.fn(this);
	}else{
		return options.inverse(this);
	}
});//注册一个用于判断是否是某行的第一个item的helper

//获取用户的作品
function getWorks(){
	$.ajax({
		url:config.api.getAllWorks[0].replace(/\<\w+\>/,pageBelongToId),
		type:config.api.getAllWorks[1],
		success:function(d){
			handlebarsRender("#works","#myWork",d);
		},
		error:function(){
			alert("获取作品失败");
		}
	});
}
function followUser (idToFollow) {
	var userId=cookie.getCookie("userId");
	if(!userId){
		alert("请先登录");
		return;
	}
	$.ajax({
		url:config.api.followUser[0].replace(/\<\w+\>/,userId),
		type:config.api.followUser[1],
		data:{
			userId:idToFollow,
			follow:1
		},
		success:function(d){
			$("#followThisGuy").attr("id","unfollowThisGuy")
							   .text("取消关注");
		},
		error:function(){
			alert("关注失败");
		}
	});
}
function unfollowUser (idToUnFollow) {
	var userId=cookie.getCookie("userId");
	if(!userId){
		alert("请先登录");
		return;
	}
	$.ajax({
		url:config.api.followUser[0].replace(/\<\w+\>/,userId),
		type:config.api.followUser[1],
		data:{
			userId:idToUnFollow,
			follow:0
		},
		success:function(d){
			$("#unfollowThisGuy").attr("id","followThisGuy")
							   .text("关注");
		},
		error:function(){
			alert("关注失败");
		}
	});
}
});
